<?php

class AuthController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        
    }

    public function loginAction() {

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->redirect('index/index');
        }
        
        $loginForm = new Application_Form_Auth();
        if ($this->getRequest()->isPost()) {
            if ($loginForm->isValid($this->_request->getPost())) {
                $adapter = $this->getAuthAdapter();
                $username = $loginForm->getValue('login');
                $password = $loginForm->getValue('password');
                $adapter->setIdentity($username)
                        ->setCredential($password);


                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);

                if ($result->isValid()) {
                    $identity = $adapter->getResultRowObject();
                    
                    $authStorage = $auth->getStorage();
                    $authStorage->write($identity);
                    
                    $this->redirect('index/index');
                }else{
                    $this->view->errorMessage = 'login ou mdp incorrect.';
                }
            }
        }
        $this->view->loginForm = $loginForm;
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->redirect('index/index');
    }

    private function getAuthAdapter() {
        $adapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $adapter->setTableName('client')
                ->setIdentityColumn('nomUtilisateur')
                ->setCredentialColumn('motDePasse');
        return $adapter;
    }

}
